package cn.itcast.mq.listener;

import cn.itcast.mq.config.CommonConfig;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = CommonConfig.DIRECT_QUEUE)
    public void listenMessage(String msg) {
        System.out.println("消费者接收到simple.queue的消息：【" + msg + "】");
        int  i = 1/0;//模拟消费者业务处理失败，手动抛出异常
    }

    /**
     * 消费者确认机制为manual方式，才用到下面的消费者代码写法
     * @param message
     * @param channel
     */
//    @RabbitListener(queues = CommonConfig.DIRECT_QUEUE)
//    public void listenMessage(Message message, Channel channel) {
//        try {
//            String msg = new String(message.getBody());
//            System.out.println("消费者接收到simple.queue的消息：【" + msg + "】");
//
//            //int  i = 1/0;//模拟消费者业务处理失败，手动抛出异常
//
//            //手动确认ack，告诉mq服务端消费者消费成功，应该删除消息
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            try {
//                //手动确认ack，告诉mq服务端消费者消费失败，应该保留消息（消息重回队列）
//                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
//            } catch (IOException ioException) {
//                ioException.printStackTrace();
//            }
//        }
//    }

    @RabbitListener(queues = CommonConfig.ERROR_QUEUE)
    public void listenErrorMsg(String msg){
        System.out.println("最后一次消费到消息：" + msg);
    }
    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "dl.queue", durable = "true")
            ,exchange = @Exchange(name = "dl.exchange", type = ExchangeTypes.DIRECT)
            ,key = "dl.key"
    ))
    public void listenDLMsg(String msg){
        System.out.println("消费到的死信消息：" + msg);
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "delay.queue", durable = "true")
            ,exchange = @Exchange(name = "delay.exchange", delayed = "true")
            ,key = "delay.key"
    ))
    public void listenDelayMsg(String msg){
        System.out.println("延迟消费的消息：" + msg);
    }
}
